package cn.sunjinxin.trade.infrastructure.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.sunjinxin.trade.dal.mapper.OrderMapper;
import cn.sunjinxin.trade.dal.po.OrderPo;
import cn.sunjinxin.trade.domain.gateway.OrderGateway;
import cn.sunjinxin.trade.domain.model.Order;
import cn.sunjinxin.trade.infrastructure.config.IdWork;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import static java.util.stream.Collectors.toList;


/**
 * @author issavior
 */
@Repository
public class OrderRepository extends ServiceImpl<OrderMapper, OrderPo> implements OrderGateway {

    @Override
    public void save(Order order) {
        OrderPo entity = new OrderPo();
        order.initId(IdWork.nextId());
        BeanUtil.copyProperties(order, entity);
        entity.setVersion(0);
        entity.setCreatedTime(new Date());
        entity.setUpdatedTime(new Date());

        if (!super.save(entity)) {
            throw new RuntimeException("保存订单失败");
        }
    }

    public Order getOrderById(Long id) {
        OrderPo orderPo = super.getById(id);
        Order order = new Order();
        BeanUtil.copyProperties(orderPo, order);
        return order;
    }

    @Override
    public void batchSave(List<Order> tpOrders) {
        super.saveBatch(tpOrders.stream().map(order -> {
            OrderPo orderPo = new OrderPo();
            BeanUtil.copyProperties(order, orderPo);
            return orderPo;
        }).collect(toList()));
    }
}
